<?php
	//Validate to see if the user has credentials to validate
	if(!array_key_exists("username", $_POST) || !array_key_exists("loginpassword", $_POST)){
		//Redirect the user with no warning, this should not happen only in a hack attemp
		header("Location: index.php");
		exit;
	}
	//User has credentials to validate
	$conn = mysql_connect("", "piedu_user", "q&&^%@8ezO8+");
	mysql_select_db("piedu_db");
	
	$clean_password = sha1(preg_replace("/[^a-zA-Z0-9_\-\s]/", "", $_POST['loginpassword'])); //Encrypted password accept alpha numeric characters and - and _
	$clean_username = preg_replace("/[^a-zA-Z0-9@\-_\.\s]/", "", $_POST['username']); //a valid email is allowed
	$sql = "select * from users where username = '$clean_username' and password = '$clean_password'";
	$query = mysql_query($sql, $conn);
	
	if(mysql_num_rows($query) == 0){
		//The user fail the login, redirect to the index page
		header("Location: index.php?login=false");
		exit;
	}
	
	//The user has good credentials, give him the welcome and create the session variable
	session_start();
	$user_data = mysql_fetch_assoc($query);
	$_SESSION['username'] = $user_data['username'];
	$_SESSION['fname'] = $user_data['fname'];
	$_SESSION['lname'] = $user_data['lname'];
	$_SESSION['account'] = $user_data['account'];
	$_SESSION['group'] = $user_data['group_code'];
	
	mysql_close($conn);
	
	//according to the user account type, redirect him
	switch($_SESSION['account']){
		case "1":
			header("Location: app/student/");
			break;
		case "2":
			header("Location: app/teacher/");
			break;
		case "3":
			header("Location: app/developer/");
			break;
		case "4":
			$_SESSION['role'] = "admin";
			header("Location: admin/index.php");
			break;
	}
?>